package Keriosity_bluetoothCommand;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class BluetoothCommand {

	private BluetoothDevice k_device = null;
	private BluetoothSocket k_socket = null;
	private InputStream k_inStream = null;
	private OutputStream k_OutStream = null;
	
	//private ReceiverThread k_receiverThread;
	//Handler k_handler;
	
	
	/** CONSTRUCTEUR **/
	public BluetoothCommand() { //Handler handStatut, Handler handThread, String name) {
	

		//k_handler = handStatut;		
		//k_receiverThread = new ReceiverThread(handThread); //thread recevant les donnees du robot
		
	}
	
	
	 /** Methode find() permettant de lister tout les peripheriques bluetooth 
     * et choisissant parmis eux notre robot
     * @param String name: nom du robot a trouver
     * @return boolean : vrai si on a trouve le robot, faux sinon
     */
	 public boolean find(String name) {
	      
	        //on capte l'ensemble des appareils equipes de bluetooth
	        Set<BluetoothDevice> setDevice = BluetoothAdapter.getDefaultAdapter().getBondedDevices(); 
	        BluetoothDevice[] device = (BluetoothDevice[]) setDevice.toArray(new BluetoothDevice[setDevice.size()]); //on cree la liste des appareils
	       
	        //On cherche dans les appareils detectes notre robot
	        for(int i = 0 ; i < device.length; i++){
	        	
	            //on va prendre l'appareil correspondant au nom
	            if(device[i].getName().contains(name)) {
	             
	            	k_device = device[i]; //on a trouve Keriosity!!
	                try {
	                    //on cree le socket
	                	k_socket = k_device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
	                     
	                	k_inStream = k_socket.getInputStream(); //canal permettant de recevoir des donnees
	                	k_OutStream = k_socket.getOutputStream();//canal permettant d'emettre des donnees	                	
	                	  
	                	return true;
	                } catch (IOException e) {}      
	            }
	        }
	        return false; //on a pas trouve notre robot
	   }
	
	
	 /** Methode permettant de se connecter au robot en bluetooth **/
	 public void connect() {
			new Thread() {
				@Override public void run() {
					try {
						
						k_socket.connect(); //on se connecte
						
						//Message msg = k_handler.obtainMessage();
						//msg.arg1 = 1;
						//k_handler.sendMessage(msg);
		                
		               // k_receiverThread.start(); //on lance le thread en ecoute
						
					} catch (IOException e) {}
				}
			}.start(); //on lance le thread qui emet
		}
	
	
	/** Methode envoyant les instructions a Keriosity
     * @param String : ordre 
     */
	 public void send(String ordre) {
	      
    	try {
        	k_OutStream.write(ordre.getBytes()); //on ecrit les ordres dans le buffer     
        	k_OutStream.flush(); //on verifie que l'envoi a fonctionne	             
        } catch (IOException e) {}
	 }
	 
	 
	 /** Methode fermant la connexion **/
	public void deconnect() {
		try {
			k_socket.close();
		} catch (IOException e) {}
	}

	
	/** Getter: on renvoi le device de notre tablette **/
	public BluetoothDevice getDevice() {return k_device;}
	
	
	
	/**** Classe de notre thread receptant les donnees en provenance de notre robot ****/	
	/*
	private class ReceiverThread extends Thread {
		
		Handler t_handler;
		
		// CONSTRUCTEUR 
		ReceiverThread(Handler hand) {
			t_handler = hand;
		}
		
		// Lancement du thread //
		@Override public void run() {
			while(true) {
				try {
					if(k_inStream.available() > 0) {

						byte buffer[] = new byte[100];
						int k = k_inStream.read(buffer, 0, 100);

						if(k > 0) {
							byte rawdata[] = new byte[k];
							for(int i=0;i<k;i++)
								rawdata[i] = buffer[i];
							
							String data = new String(rawdata);

							Message msg = t_handler.obtainMessage();
							Bundle b = new Bundle();
							b.putString("receivedData", data);
			                msg.setData(b);
			                t_handler.sendMessage(msg);
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}//ReceiverThread
	*/
}//BluetoothCommand
